<template>
  <view class="assistant-page" :style="{ paddingTop: statusBarHeight + 'px' }">
    <!-- 对话区域 -->
    <scroll-view scroll-y class="chat-container" :scroll-into-view="scrollToView" scroll-with-animation>
      <view class="message-list">
        <!-- 消息列表（AI+用户） -->
        <view class="message-item" v-for="(msg, index) in messages" :key="index" :id="'msg' + index">
          <!-- AI消息 -->
          <view v-if="msg.type === 'ai'" class="message-wrapper">
            <image src="/static/images/ai-assistant.png" mode="aspectFill" class="avatar" />
            <view class="message-content-wrapper">
              <view class="message-bubble ai-bubble">
                <text class="message-text" v-if="msg.content">{{ msg.content }}</text>
                <!-- 显示图片 -->
                <image 
                  v-if="msg.imageUrl" 
                  :src="msg.imageUrl" 
                  mode="widthFix" 
                  class="message-image"
                  @tap="previewImage(msg.imageUrl)"
                />
                <view class="typing-indicator" v-else>
                  <span></span><span></span><span></span>
                </view>
              </view>
              <text class="message-time">{{ msg.time }}</text>
            </view>
          </view>
          <!-- 用户消息（多图展示） -->
          <view v-else class="message-wrapper user-wrapper">
            <view class="message-content-wrapper user-content">
              <view class="message-bubble user-bubble">
                <text class="message-text">{{ msg.content }}</text>
                <!-- 消息中的多图展示 -->
                <view class="message-images-group" v-if="msg.imageUrls && msg.imageUrls.length > 0">
                  <view class="message-image-item" v-for="(imgUrl, idx) in msg.imageUrls" :key="idx">
                    <!-- 传入当前图片的URL -->
                    <image :src="imgUrl" mode="aspectFill" class="message-image" @tap="previewImageGroupFromMsg(msg.imageUrls, imgUrl)"></image>
                  </view>
                </view>
              </view>
              <text class="message-time">{{ msg.time }}</text>
            </view>
            <image :src="userUrl || '/static/images/user-avatar.png'" mode="aspectFill" class="avatar" />
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部功能区 -->
    <view class="bottom-actions">
      <view class="action-buttons">
        <view class="action-btn" @tap="handleHealthCheck">
          <text class="btn-icon">❤️</text>
          <text class="btn-text">健康评估</text>
        </view>
        <view class="action-btn" @tap="handlePersonalPlan">
          <text class="btn-icon">📋</text>
          <text class="btn-text">日程提醒</text>
        </view>
      </view>
<!-- 已选图片预览区：多图网格 -->
<view class="selected-images-preview" v-if="selectedImages.length > 0">
  <!-- 已选图片列表 -->
  <view class="selected-image-item" v-for="(imgPath, index) in selectedImages" :key="index">
    <image :src="imgPath" mode="aspectFill" class="preview-image" @tap="previewImageGroup(imgPath)"></image>
        <view class="delete-image-btn" @tap.stop="deleteSingleImage(index)">
          <text class="iconfont">×</text>
        </view>
  </view>
  <!-- 添加图片按钮（还有剩余名额时显示） -->
  <view class="add-image-btn" @tap="chooseImage" v-if="selectedImages.length < 3">
    <text class="iconfont">+</text>
  </view>
</view>
      <!-- 输入框 -->
      <view class="input-area">
        <input v-model="inputText" 
               class="message-input" 
               placeholder="输入你的问题..." 
               confirm-type="send"
               @confirm="sendMessage" 
               @input="handleInput" />
        <!-- 图片上传按钮 -->
        <view class="upload-btn" @tap="chooseImage">
          <text class="iconfont">🖼️</text>
        </view>
        <!-- 发送按钮 -->
        <view class="send-btn" @tap="sendMessage" :class="{ disabled: !inputText.trim() && selectedImages.length === 0 }">
          <text class="iconfont">➤</text>
        </view>
      </view>
    </view> 
    
    <!-- 未登录提示 -->
    <LoginPrompt 
      :is-login="isLogin" 
      prompt-text="请登录后使用智慧管家"
      @goToLogin="goToLogin"
    />
  </view>
</template>

<script setup>
import { ref, nextTick, onMounted, onUnmounted } from 'vue'
import { onShow } from '@dcloudio/uni-app';
import userManager from '../../common/utils/user.js'
import systemUtils from '../../common/utils/system.js'
import LoginPrompt from '../../components/LoginPrompt.vue'
// 引入完善后的接口（新增 uploadImage）
import { AIStream, uploadImage } from '../../api/AIapi.js'

const userUrl = ref(userManager.getUserInfo()?.avatarUrl)
// 获取当前时间（不变）
const getCurrentTime = () => {
  const now = new Date()
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

// 1. 状态管理
const selectedImages = ref([]) // 存储选中的所有图片临时路径（数组）
const statusBarHeight = ref(0) 
const messages = ref([ 
  {
    type: 'ai',
    content: '你好！我是你的宠物智慧管家小宠，有什么可以帮助你的吗？😊',
    time: getCurrentTime()
  }
])
const inputText = ref('') 
const scrollToView = ref('') 
const isLogin = ref(false) 
const sessionId = ref('') 
const isAISending = ref(false) 

// 2. 页面生命周期（不变）
onMounted(() => {
  statusBarHeight.value = systemUtils.getStatusBarHeight()
  checkLoginStatus()
  initSessionId()
  scrollToBottom()
  uni.$on('loginStatusChanged', handleLoginStatusChanged)
})

onUnmounted(() => {
  uni.$off('loginStatusChanged', handleLoginStatusChanged)
})

// 在 onMounted 之后添加 onShow 生命周期
onShow(() => {
  // 从缓存读取多图数组（JSON字符串转数组）
  const cachedImagesStr = uni.getStorageSync('chatSelectedImages')
  if (cachedImagesStr) {
    const cachedImages = JSON.parse(cachedImagesStr)
    selectedImages.value = cachedImages
    console.log('恢复多图状态，已选数量:', cachedImages.length);
  }
})

// 3. 选择图片（不变，仅后续调用 uploadImage 接口）
const chooseImage = () => {
  if (!userManager.checkLogin()) {
    showLoginPrompt()
    return
  }
  
  // 最多选择3张图（可根据需求调整，如9张）
    const maxSelectCount = 3 
    const remainingCount = maxSelectCount - selectedImages.value.length // 剩余可选择数量
  
    if (remainingCount <= 0) {
      uni.showToast({ title: `最多选择${maxSelectCount}张图片`, icon: 'none' })
      return
    }

  uni.chooseImage({
    count: remainingCount,
    sourceType: ['album', 'camera'],
    sizeType: ['compressed'],
    success: (res) => {
      // 将新选中的图片添加到数组（... 展开原有数组，避免覆盖）
            const newSelectedImages = [...selectedImages.value, ...res.tempFilePaths]
            selectedImages.value = newSelectedImages
      
            // 保存到本地缓存（多图用JSON字符串存储数组）
            uni.setStorageSync('chatSelectedImages', JSON.stringify(newSelectedImages))
      
            console.log('选择图片成功，已选数量:', newSelectedImages.length);
            console.log('已选图片路径:', newSelectedImages);
                },
          fail: (err) => {
            console.error('选择图片失败:', err)
            if (err.errMsg !== 'chooseImage:fail cancel') {
              uni.showToast({ title: '选择图片失败，请重试', icon: 'none' })
            }
          }
        })
      }
// 4. 核心：发送消息（修复流式解析+图片上传接口）
const sendMessage = async () => {
  // 防重复发送 + 空内容校验（有文字或有图片即可发送）
  if (isAISending.value || (!inputText.value.trim() && selectedImages.value.length === 0)) return
  
  // 登录校验
  if (!userManager.checkLogin()) {
    showLoginPrompt()
    return
  }

  const currentTime = getCurrentTime()
  let userMsgContent = inputText.value.trim()
  const ossImageUrls = [] // 存储所有图片的OSS URL（数组）

  // 1. 批量上传多图（循环调用上传接口）
  if (selectedImages.value.length > 0) {
    try {
      uni.showLoading({ title: `上传中(${0}/${selectedImages.value.length})` })
      
      // 循环上传每张图片
      for (let i = 0; i < selectedImages.value.length; i++) {
        const tempPath = selectedImages.value[i]
        // 调用上传接口，传入临时路径
        const ossUrl = await uploadImage(
          tempPath, 
          sessionId.value
        )
        ossImageUrls.push(ossUrl) // 收集OSS URL
        
        // 更新加载提示（显示当前上传进度）
        uni.showLoading({ title: `上传中(${i+1}/${selectedImages.value.length})` })
        console.log(`第${i+1}张图片上传成功，OSS URL:`, ossUrl);
      }

      uni.hideLoading()
      // 上传成功后，清空多图状态和缓存
      selectedImages.value = []
      uni.removeStorageSync('chatSelectedImages')

      // 处理消息内容（纯图片/图文结合）
      if (!userMsgContent) {
        userMsgContent = `[${ossImageUrls.length}张图片]`
      } else {
        userMsgContent += `（附${ossImageUrls.length}张图片）`
      }
    } catch (err) {
      uni.hideLoading()
      console.error('图片上传失败:', err.message)
      uni.showToast({ title: `上传失败：${err.message}`, icon: 'none' })
      return 
    }
  }

  // 2. 添加用户消息到列表（显示所有图片）
  const userMsg = {
    type: 'user',
    content: userMsgContent,
    time: currentTime,
    imageUrls: ossImageUrls // 存储多图的OSS URL（数组）
  }
  messages.value.push(userMsg)
  inputText.value = '' // 清空输入框
  scrollToBottom()

  // 3. 准备AI回复（不变）
  isAISending.value = true
  const aiMsgIndex = messages.value.length
  messages.value.push({ type: 'ai', content: '', time: currentTime })
  scrollToBottom()

  // 4. 调用AI接口：传入多图OSS URL数组
  try {
    const requestData = {
      question: userMsgContent,
      sessionId: sessionId.value,
      filesPath: ossImageUrls, // 关键：传多图URL数组给AI
    }

    // 调用你的AIStream接口（确保后端能接收filesPath参数）
    const response = await AIStream(requestData)
    console.log('AI接口响应:', response)

    if (response.statusCode === 200 && response.data) {
      // 解析后端流式响应（按你的格式拆分）
      const rawChunks = response.data.split('data:')
      const textChunks = rawChunks
        .filter(chunk => chunk.trim() !== '')
        .map(chunk => chunk.replace(/\n/g, ''))

      // 打字机效果拼接AI回复
      for (const chunk of textChunks) {
        if (chunk) {
          messages.value[aiMsgIndex].content += chunk
          scrollToBottom()
          await new Promise(resolve => setTimeout(resolve, 100))
        }
      }
    } else {
      messages.value[aiMsgIndex].content = '抱歉，请求失败，请重试~'
    }
  } catch (error) {
    messages.value[aiMsgIndex].content = '抱歉，暂时无法获取回复~'
    console.error('AI请求错误:', error)
  } finally {
    isAISending.value = false
  }
}

// 删除单张已选图片（按索引删除）
const deleteSingleImage = (index) => {
  // 复制原数组，避免直接修改响应式数据
  const newImages = [...selectedImages.value]
  newImages.splice(index, 1) // 删除指定索引的图片
  selectedImages.value = newImages

  // 更新缓存（空数组时清除缓存）
  if (newImages.length > 0) {
    uni.setStorageSync('chatSelectedImages', JSON.stringify(newImages))
  } else {
    uni.removeStorageSync('chatSelectedImages')
  }

  console.log('删除单张图片，剩余数量:', newImages.length);
}

// 点击预览区图片时预览所有已选图
const previewImageGroup = (currentImagePath) => {
  if (selectedImages.value.length === 0) return
  uni.previewImage({
    urls: selectedImages.value, // 所有已选图片的数组（正确）
    current: currentImagePath, // 传入当前点击的图片路径（关键修正）
    longPressActions: { itemList: [], fail: () => {} }
  })
}
// 预览消息中的多图
const previewImageGroupFromMsg = (imageUrls, currentImageUrl) => {
  uni.previewImage({
    urls: imageUrls,
    current: currentImageUrl, // 传入当前点击的图片URL
    longPressActions: { itemList: [], fail: () => {} }
  })
}

// 其他方法（预览图片、滚动到底部等，均不变）
const previewImage = (imageUrl) => {
  uni.previewImage({
    urls: [imageUrl],
    current: imageUrl,
    loop: false
  })
}

const scrollToBottom = () => {
  nextTick(() => {
    const lastIndex = messages.value.length - 1
    scrollToView.value = 'msg' + lastIndex
  })
}

const checkLoginStatus = () => {
  isLogin.value = userManager.checkLogin()
  if (!isLogin.value) {
    showLoginPrompt()
  }
}

const handleLoginStatusChanged = (loginStatus) => {
  isLogin.value = loginStatus
  if (!loginStatus) {
    uni.switchTab({ url: '/pages/mine/mine' })
  }
}

const initSessionId = () => {
  const storedSessionId = uni.getStorageSync('petChatSessionId')
  if (storedSessionId) {
    sessionId.value = storedSessionId
  } else {
    const timestamp = new Date().getTime()
    const randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
    const newSessionId = `chat_${timestamp}_${randomNum}`
    sessionId.value = newSessionId
    uni.setStorageSync('petChatSessionId', newSessionId)
  }
}

const showLoginPrompt = () => {
  uni.showToast({ title: '请先登录', icon: 'none', duration: 1500 })
  setTimeout(() => {
    uni.switchTab({ url: '/pages/mine/mine' })
  }, 1500)
}

const goToLogin = () => {
  uni.switchTab({ url: '/pages/mine/mine' })
}

const handleHealthCheck = () => {
  if (!userManager.checkLogin()) {
    showLoginPrompt()
    return
  }
  uni.showToast({ title: '启动健康评估', icon: 'none' })
}

const handlePersonalPlan = () => {
  if (!userManager.checkLogin()) {
    showLoginPrompt()
    return
  }
  uni.showToast({ title: '进入日程提醒', icon: 'none' })
  uni.navigateTo({ url: '/pages/schedule/schedule' })
}

const handleInput = (e) => {
  const maxLength = 500
  if (e.detail.value.length > maxLength) {
    inputText.value = e.detail.value.substring(0, maxLength)
    uni.showToast({ title: `最多输入${maxLength}个字符`, icon: 'none', duration: 1000 })
  }
}
</script>

<style scoped>
	/* 用户消息中的多图组 */
	.message-images-group {
	  display: flex;
	  flex-wrap: wrap;
	  gap: 8rpx;
	  margin-top: 16rpx;
	}
	
	/* 消息中的单张图片 */
	.message-image-item {
	  width: 100rpx;
	  height: 100rpx;
	  border-radius: 12rpx;
	  overflow: hidden;
	}
	
	/* 消息图片（复用原有样式，调整大小） */
	.message-image {
	  width: 100%;
	  height: 100%;
	}
	/* 多图预览区：网格布局 */
	.selected-images-preview {
	  display: flex;
	  flex-wrap: wrap;
	  gap: 16rpx;
	  margin: 16rpx 0 16rpx 32rpx;
	}
	
	/* 单张已选图片容器 */
	.selected-image-item {
	  position: relative;
	  width: 120rpx;
	  height: 120rpx;
	  border-radius: 16rpx;
	  overflow: hidden;
	  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}
	
	/* 预览图片 */
	.preview-image {
	  width: 100%;
	  height: 100%;
	}
	
	/* 单张图片删除按钮 */
	.delete-image-btn {
	  position: absolute;
	  top: -10rpx;
	  right: -10rpx;
	  width: 40rpx;
	  height: 40rpx;
	  background-color: rgba(255, 68, 68, 0.9);
	  color: white;
	  border-radius: 50%;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  font-size: 24rpx;
	  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
	}
	
	/* 多图模式的添加按钮 */
	.add-image-btn {
	  width: 120rpx;
	  height: 120rpx;
	  border: 2rpx dashed #C9CDD4;
	  border-radius: 16rpx;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  font-size: 36rpx;
	  color: #94A3B8;
	  background-color: #F8FAFC;
	}
	/* 全局基础样式 */
	.assistant-page {
	  height: 93vh;
	  display: flex;
	  flex-direction: column;
	  background-color: #F5F5F5;
	  overflow: hidden;
	}
	
	/* 对话区域样式 */
	.chat-container {
	  flex: 1;
	  padding: 32rpx;
	  padding-bottom: 0;
	  overflow-y: auto;
	  -webkit-overflow-scrolling: touch; /* 优化iOS滚动体验 */
	}
	
	.message-list {
	  width: 95vw;
	  display: flex;
	  flex-direction: column;
	  gap: 32rpx;
	  padding-bottom: 32rpx;
	}
	
	.message-item {
	  width: 100%;
	  display: flex;
	  margin: 8rpx 0;
	}
	
	/* 消息容器样式 */
	.message-wrapper {
	  display: flex;
	  align-items: flex-start;
	  max-width: 85%; /* 限制消息最大宽度，避免过宽 */
	}
	
	.user-wrapper {
	  justify-content: flex-end;
	  margin-left: auto; /* 右对齐用户消息 */
	}
	
	.avatar {
	  width: 80rpx;
	  height: 80rpx;
	  border-radius: 50%;
	  flex-shrink: 0; /* 防止头像被压缩 */
	  margin-top: 8rpx;
	  background-color: #EEEEEE; /* 占位背景 */
	  overflow: hidden;
	}
	
	.message-content-wrapper {
	  display: flex;
	  flex-direction: column;
	  max-width: calc(100% - 120rpx); /* 减去头像宽度和间距 */
	  margin: 0 24rpx;
	}
	
	.user-content {
	  align-items: flex-end; /* 用户消息右对齐 */
	}
	
	/* 消息气泡样式 */
	.message-bubble {
	  padding: 24rpx 32rpx;
	  border-radius: 24rpx;
	  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
	  position: relative;
	  word-break: break-all;
	  line-height: 1.6;
	}
	
	.ai-bubble {
	  background-color: #FFFFFF;
	  border-top-left-radius: 8rpx; /* 左侧尖角效果 */
	}
	
	.user-bubble {
	  background: linear-gradient(135deg, #89CFF0 0%, #B7F0AD 100%);
	  border-top-right-radius: 8rpx; /* 右侧尖角效果 */
	}
	
	/* 消息内容样式 */
	.message-text {
	  font-size: 28rpx;
	  color: #333333;
	}
	
	.user-bubble .message-text {
	  color: #FFFFFF;
	}
	
	/* 消息图片样式 */
	.message-image {
	  width: 100%;
	  max-width: 300rpx; /* 限制图片最大宽度 */
	  border-radius: 16rpx;
	  margin-top: 16rpx;
	  margin-bottom: 8rpx;
	  cursor: pointer;
	  display: block; /* 避免图片底部间隙 */
	}
	
	/* 消息时间样式 */
	.message-time {
	  font-size: 20rpx;
	  color: #999999;
	  margin-top: 8rpx;
	  align-self: flex-start;
	  padding: 0 8rpx;
	}
	
	.user-content .message-time {
	  align-self: flex-end;
	}
	
	/* AI加载动画 */
	.typing-indicator {
	  display: flex;
	  gap: 8rpx;
	  padding: 16rpx 0;
	  align-items: center;
	  justify-content: flex-start;
	}
	
	.typing-indicator span {
	  width: 12rpx;
	  height: 12rpx;
	  border-radius: 50%;
	  background-color: #89CFF0;
	  animation: typing 1.4s infinite ease-in-out both;
	}
	
	.typing-indicator span:nth-child(1) {
	  animation-delay: -0.32s;
	}
	
	.typing-indicator span:nth-child(2) {
	  animation-delay: -0.16s;
	}
	
	@keyframes typing {
	  0%, 80%, 100% {
	    transform: scale(0);
	  }
	  40% {
	    transform: scale(1);
	  }
	}
	
	/* 底部功能区样式 */
	.bottom-actions {
	  background-color: #FFFFFF;
	  padding: 24rpx 32rpx;
	  border-top: 1px solid #F0F0F0;
	  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.03); /* 顶部阴影 */
	}
	
	.action-buttons {
	  display: flex;
	  gap: 24rpx;
	  margin-bottom: 24rpx;
	}
	
	.action-btn {
	  flex: 1;
	  background: linear-gradient(135deg, #FFD1DC 0%, #89CFF0 100%);
	  border-radius: 16rpx;
	  padding: 24rpx 16rpx;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  gap: 12rpx;
	  color: #FFFFFF;
	  font-weight: 500;
	  cursor: pointer;
	  transition: transform 0.2s;
	}
	
	.action-btn:active {
	  transform: scale(0.98); /* 点击缩放效果 */
	}
	
	.btn-icon {
	  font-size: 32rpx;
	}
	
	.btn-text {
	  font-size: 28rpx;
	}
	
	/* 输入区域样式 */
	.input-area {
	  display: flex;
	  align-items: center;
	  gap: 16rpx;
	}
	
	.message-input {
	  flex: 1;
	  background-color: #F5F5F5;
	  border-radius: 999rpx;
	  padding: 20rpx 32rpx;
	  font-size: 28rpx;
	  min-height: 80rpx;
	  max-height: 160rpx;
	  line-height: 40rpx;
	  border: none;
	  outline: none;
	  resize: none; /* 禁止手动调整大小 */
	}
	
	/* 上传按钮样式 */
	.upload-btn {
	  width: 80rpx;
	  height: 80rpx;
	  border-radius: 50%;
	  background-color: #F5F5F5;
	  color: #666666;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  font-size: 36rpx;
	  cursor: pointer;
	  transition: background-color 0.2s;
	}
	
	.upload-btn:active {
	  background-color: #E8E8E8;
	}
	
	/* 发送按钮样式 */
	.send-btn {
	  width: 80rpx;
	  height: 80rpx;
	  border-radius: 50%;
	  background-color: #89CFF0;
	  color: #FFFFFF;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  font-size: 36rpx;
	  cursor: pointer;
	  transition: background-color 0.2s, transform 0.2s;
	}
	
	.send-btn:active {
	  transform: scale(0.95);
	  background-color: #76BFE0;
	}
	
	.send-btn.disabled {
	  background-color: #E0E0E0;
	  color: #FFFFFF;
	  cursor: not-allowed;
	}
	
	/* 未登录提示样式（适配组件） */
	.login-prompt {
	  position: fixed;
	  bottom: 200rpx;
	  left: 50%;
	  transform: translateX(-50%);
	  background-color: rgba(0, 0, 0, 0.7);
	  color: white;
	  padding: 24rpx 48rpx;
	  border-radius: 999rpx;
	  font-size: 28rpx;
	  z-index: 999;
	  animation: fadeIn 0.3s;
	}
	
	@keyframes fadeIn {
	  from { opacity: 0; transform: translate(-50%, 20rpx); }
	  to { opacity: 1; transform: translate(-50%, 0); }
	}
	
	/* 响应式适配（小屏设备） */
	@media (max-width: 375px) {
	  .message-bubble {
	    padding: 20rpx 24rpx;
	  }
	  
	  .message-text {
	    font-size: 26rpx;
	  }
	  
	  .action-btn {
	    padding: 20rpx 12rpx;
	  }
	  
	  .btn-text {
	    font-size: 26rpx;
	  }
	}
</style>